﻿using RhotCMS.Controllers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace RhotCMS.Filters
{
    public class RhotCMSAuthorizeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            RhotCMSController controller = (RhotCMSController)filterContext.Controller;
            var isAlowed = controller.IsAlowed;
            var uiLang = CultureInfo.GetCultureInfo(controller.UILangName).TwoLetterISOLanguageName;           
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName = (string)filterContext.RouteData.Values["action"];

            if (!isAlowed)
            {
                var url = filterContext.HttpContext.Request.RawUrl;

                if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    var routeValueDictionary = filterContext.RouteData;

                    filterContext.Result = new RedirectToRouteResult("Account", 
                        new RouteValueDictionary(new
                        {
                            lang = uiLang,
                            controller = "Account",
                            action = "Login",
                            returnUrl = url
                        })
                    );
                 
                }

                else if (!actionName.Equals("YouHaveNoPermission", StringComparison.InvariantCultureIgnoreCase))
                {
                    var routeValueDictionary = filterContext.RouteData;

                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(new
                    {
                        controller = controllerName,
                        action = "YouHaveNoPermission"
                    })
                    );
                }
            }
        }
    }
}